package mt521.cam.ac.uk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;

import org.apache.commons.io.IOUtils;

public class FileOperators {

    public static byte[] convertToBytes(File file) {
        byte[] byteFile = null;
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            byteFile = IOUtils.toByteArray(fis);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return byteFile;
    }
    
    public static File convertToFile(byte[] bData, String filename) {
        File file = new File(filename+".txt");
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            fos.write(bData);
            fos.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    
    public static byte[] mic(int bytes) {
        int toRead = Encode.getChunkSize()*bytes;
        int readSoFar = 0;
        int num = 16384;         //random large power of 2
        byte[] buffer = new byte[num];
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        
        AudioFormat af = new AudioFormat(Encode.getSampleRate(),8,1,true,false);
        
        DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, af);
        Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
        Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

        try {
            TargetDataLine microphone = (TargetDataLine) mixer.getLine(dataLineInfo);
            microphone.open(af);
            microphone.start();
            
            while (readSoFar<toRead) {
                readSoFar += microphone.read(buffer,0,num); //returns int saying how many bytes were read
                stream.write(buffer);
            }
        }
        catch (LineUnavailableException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        byte[] sound = stream.toByteArray();
        return sound;
    }
    
}
